// 确保DOM完全加载后再执行代码
$(document).ready(function(){
	// 搜索引擎配置对象
	var searchEngineConfig = {
		baidu: {
			name: '百度',
			action: 'https://www.baidu.com/s',
			param: 'wd',
			icon: 'img/baidu.png'
		},
		yandex: {
			name: 'Yandex',
			action: 'https://yandex.com/search',
			param: 'text',
			icon: 'img/yandex.png'
		},
		bing: {
			name: '必应',
			action: 'https://www.bing.com/search',
			param: 'q',
			icon: 'img/bing.png'
		},
		so: {
			name: '360搜索',
			action: 'https://www.so.com/s',
			param: 'q',
			icon: 'img/360.png'
		},
		sogou: {
			name: '搜狗',
			action: 'https://www.sogou.com/web',
			param: 'query',
			icon: 'img/sogo.png'
		}
	};
	
	// 初始化搜索引擎选择器
	function initSearchEngineSelector() {
		var searchEngineIcon = document.getElementById('searchEngineIcon');
		var searchEngineDropdown = document.getElementById('searchEngineDropdown');
		var engineOptions = document.querySelectorAll('.engine-option');
		
		// 从存储中获取当前搜索引擎并设置图标
		chrome.storage.local.get(['searchEngine'], function(result) {
			var engine = result.searchEngine || 'baidu';
			if (searchEngineConfig[engine]) {
				$('.engine-icon-img').attr('src', searchEngineConfig[engine].icon);
				$('.engine-icon-img').attr('alt', searchEngineConfig[engine].name);
			}
		});
		
		// 切换下拉菜单显示状态
		searchEngineIcon.addEventListener('click', function(e) {
			e.stopPropagation();
			searchEngineDropdown.classList.toggle('show');
			$('.dropdown-arrow').css('transform', searchEngineDropdown.classList.contains('show') ? 'rotate(180deg)' : 'rotate(0)');
		});
		
		// 选择搜索引擎
		engineOptions.forEach(function(option) {
			option.addEventListener('click', function(e) {
				e.stopPropagation();
				var engine = this.getAttribute('data-engine');
				if (searchEngineConfig[engine]) {
					// 更新图标
					$('.engine-icon-img').attr('src', searchEngineConfig[engine].icon);
					$('.engine-icon-img').attr('alt', searchEngineConfig[engine].name);
												
					// 更新表单设置
					var searchForm = $('#searchContainer form');
					var searchInput = $('#searchContainer input');
					searchForm.attr('action', searchEngineConfig[engine].action);
					searchInput.attr('name', searchEngineConfig[engine].param);
					
					// 保存到存储
					chrome.storage.local.set({searchEngine: engine});
				}
				// 隐藏下拉菜单
				searchEngineDropdown.classList.remove('show');
				$('.dropdown-arrow').css('transform', 'rotate(0)');
			});
		});
		
		// 点击其他地方关闭下拉菜单
		document.addEventListener('click', function() {
			searchEngineDropdown.classList.remove('show');
			$('.dropdown-arrow').css('transform', 'rotate(0)');
		});
	}
	
	// 添加Chrome扩展环境检测
	if (typeof chrome === 'undefined' || typeof chrome.storage === 'undefined') {
		console.warn('Chrome扩展环境未检测到，将使用本地存储替代');
		// 创建模拟的chrome.storage.local对象
		window.chrome = window.chrome || {};
		chrome.storage = chrome.storage || {};
		chrome.storage.local = {
			get: function(keys, callback) {
				var result = {};
				if (Array.isArray(keys)) {
					keys.forEach(function(key) {
						result[key] = localStorage.getItem(key);
						// 尝试解析JSON字符串
						try { result[key] = JSON.parse(result[key]); } catch(e) {}
					});
				} else if (typeof keys === 'object') {
					Object.keys(keys).forEach(function(key) {
						var value = localStorage.getItem(key);
						result[key] = value !== null ? 
								// 尝试解析JSON字符串
								(typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) ? 
										JSON.parse(value) : value : 
								keys[key];
					});
				}
				callback(result);
			},
			set: function(items, callback) {
				Object.keys(items).forEach(function(key) {
					localStorage.setItem(key, JSON.stringify(items[key]));
				});
				if (callback) callback();
			},
			remove: function(keys, callback) {
				if (Array.isArray(keys)) {
					keys.forEach(function(key) {
						localStorage.removeItem(key);
					});
				} else {
					localStorage.removeItem(keys);
				}
				if (callback) callback();
			}
		};
	}
	
	// 先初始化设置面板，确保事件监听器被绑定
	initSettingsPanel();
	
	// 初始化搜索引擎选择器
	initSearchEngineSelector();
	
	// 然后处理壁纸显示
	chrome.storage.local.get(['isCustomWallpaper', 'isCustomWallpaperVideo', 'customWallpaperData', 'search', 'searchEngine', 'hideTime'], function(result) {
		// 处理壁纸显示
		if(result.isCustomWallpaper === true && result.customWallpaperData) {
			if(result.isCustomWallpaperVideo) {
				$("#video").attr('src', result.customWallpaperData);
				$("#video").show();
				$("body").css('background-image', 'none');
				// 确保视频自动播放
				$("#video").prop({muted: true, autoplay: true, loop: true});
			} else {
				$("#video").hide();
				$("body").css('background-image', 'url("'+result.customWallpaperData+'")');
			}
		} else {
			// 加载默认壁纸
			chrome.storage.local.get(['name'], function(nameResult) {
				var name = nameResult.name;
				if(name != null) {
					if(checkType(name)) {
						$("#video").attr('src', "video/"+name);
						$("#video").show();
						// 确保视频自动播放
						$("#video").prop({muted: true, autoplay: true, loop: true});
					} else {
						$("#video").hide();
						$("body").css('background-image', 'url("image/"+name+")');
					}
				}
			});
		}

		// 处理搜索框显示和搜索引擎设置
		var searchContainer = $("#searchContainer");
		var searchForm = $("#searchContainer form");
		var searchInput = $("#searchContainer input");
		var searchEngine = result.searchEngine || 'baidu';
		
		if(result.search === true) {
			searchContainer.hide();
		} else {
			searchContainer.show();
			// 设置搜索引擎
			if (searchEngineConfig[searchEngine]) {
				// 设置表单的action和method
				searchForm.attr('action', searchEngineConfig[searchEngine].action);
				searchForm.attr('method', 'get');
				
				// 设置搜索输入框的name属性
				searchInput.attr('name', searchEngineConfig[searchEngine].param);
				
				// 更新搜索图标显示
				$('.engine-icon-img').attr('src', searchEngineConfig[searchEngine].icon);
				$('.engine-icon-img').attr('alt', searchEngineConfig[searchEngine].name);
			} else {
				// 默认使用百度
				searchForm.attr('action', 'https://www.baidu.com/s');
				searchInput.attr('name', 'wd');
				$('.engine-icon-img').attr('src', 'img/baidu.png');
				$('.engine-icon-img').attr('alt', '百度');
			}
		}

		// 处理时间显示
		if(result.hideTime !== true) {
			initTimeDisplay();
		} else {
			$("#timeDisplay").hide();
		}
	});
});

// 初始化设置面板
function initSettingsPanel() {
	var settingsButton = document.getElementById('settingsButton');
	var settingsPanel = document.getElementById('settingsPanel');
	var closeSettings = document.getElementById('closeSettings');
	var switchButton = document.getElementById('switchButton');
	var timeButton = document.getElementById('timeButton');
	var fileInput = document.getElementById('file');
	var clearCustomWallpaperContainer = document.getElementById('clearCustomWallpaperContainer');
	var clearCustomWallpaper = document.getElementById('clearCustomWallpaper');

	// 从chrome.storage.local获取设置
	chrome.storage.local.get(['search', 'hideTime', 'isCustomWallpaper'], function(result) {
		if (result.search === true) {
			switchButton.checked = true;
		}
		
		if (result.hideTime === true) {
			timeButton.checked = true;
		}
		
		if(result.isCustomWallpaper === true) {
			clearCustomWallpaperContainer.style.display = 'block';
		}
	});
	
	// 使用jQuery的方式绑定事件，提高兼容性
	$(settingsButton).click(function() {
		$(settingsPanel).addClass('show');
	});
	
	$(closeSettings).click(function() {
		$(settingsPanel).removeClass('show');
	});
	
	// 点击其他区域时收起设置面板
	$(document).click(function(event) {
		// 如果点击的不是设置面板且不是设置按钮
		if (!$(settingsPanel).is(event.target) && $(settingsPanel).has(event.target).length === 0 && 
			!$(settingsButton).is(event.target) && $(settingsButton).has(event.target).length === 0) {
			// 如果设置面板当前是显示状态，则关闭它
			if ($(settingsPanel).hasClass('show')) {
				$(settingsPanel).removeClass('show');
			}
		}
	});
	
	$(switchButton).click(function() {
		chrome.storage.local.set({search: $(switchButton).prop('checked')});
		// 立即应用搜索框显示/隐藏设置
		$(document.getElementById('searchContainer')).toggle(!$(switchButton).prop('checked'));
	});
	
	$(timeButton).click(function() {
		chrome.storage.local.set({hideTime: $(timeButton).prop('checked')});
		// 立即应用时间显示/隐藏设置
		var timeDisplay = $(document.getElementById('timeDisplay'));
		timeDisplay.toggle(!$(timeButton).prop('checked'));
		// 如果时间显示之前是隐藏的，现在需要初始化
		if(timeDisplay.is(':visible') && timeDisplay.text() === '') {
			initTimeDisplay();
		}
	});
	
	$(fileInput).change(function() {
		var file = $(fileInput).prop('files')[0];
		if (file.size > 10 * 1024 * 1024) {
			alert('文件过大，建议上传小于10MB的文件以获得更好的性能');
		}

		var reader = new FileReader();

		reader.onload = function() {
			var dataURL = reader.result;
			let mime = dataURL.match(/:(.*?);/)[1];
			let isVideo = ['video/mp4', 'video/webm', 'video/ogg'].indexOf(mime.toLowerCase()) !== -1;
			
			// 将所有壁纸数据存储到chrome.storage.local
			chrome.storage.local.set({
				isCustomWallpaper: true,
				isCustomWallpaperVideo: isVideo,
				customWallpaperFileName: file.name,
				customWallpaperFileType: file.type,
				customWallpaperData: dataURL
			}, function() {
				// 立即应用壁纸
				if(isVideo) {
					$("#video").attr('src', dataURL).show();
					$('body').css('background-image', 'none');
					$("#video").prop({muted: true, autoplay: true, loop: true});
				} else {
					$("#video").hide();
					$('body').css('background-image', 'url("'+dataURL+'")');
				}
				$(clearCustomWallpaperContainer).show();
			});
		};

		if (file) {
			reader.readAsDataURL(file);
		}
	});
	
	$(clearCustomWallpaper).click(function() {
		// 清除chrome.storage.local中的壁纸数据
		chrome.storage.local.remove(['isCustomWallpaper', 'isCustomWallpaperVideo', 'customWallpaperData', 'customWallpaperFileName', 'customWallpaperFileType']);
		
		$(clearCustomWallpaperContainer).hide();
		
		// 立即应用清除壁纸的效果
		$("#video").hide();
		$('body').css('background-image', 'none');
		
		// 加载默认壁纸
		chrome.storage.local.get(['name'], function(result) {
			var name = result.name;
			if(name != null) {
				if(checkType(name)) {
					$("#video").attr('src', "video/"+name).show();
					// 确保视频自动播放
					$("#video").prop({muted: true, autoplay: true, loop: true});
				} else {
					$("#video").hide();
					$('body').css('background-image', 'url("image/"+name+")');
				}
			}
		});
	});
}

//判断是否是视频
function checkType(name) {
	var index = name.lastIndexOf(".");
	var ext = name.substr(index+1);
	return ['mp4', 'webm', 'ogg'].indexOf(ext.toLowerCase()) !== -1;
}

// 初始化时间显示
function initTimeDisplay() {
	var timeDisplay = $("#timeDisplay");
	
	function updateTime() {
		var now = new Date();
		var hours = now.getHours().toString().padStart(2, '0');
		var minutes = now.getMinutes().toString().padStart(2, '0');
		var seconds = now.getSeconds().toString().padStart(2, '0');
		timeDisplay.text(hours + ':' + minutes + ':' + seconds);
	}
	
	updateTime();
	setInterval(updateTime, 1000);
}